import { Button, Form, Input, Toast } from "antd-mobile";
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { Cell, Checkbox, CellGroup } from "react-vant";
import { addPerson, switchPerson } from "../../store/module/person";
import axios from 'axios'
function Index({ close }) {
  const onFinish = (value) => {
    console.log(value);
    Toast.show('添加成功')
    close();
  };
  const list = useSelector((state) => state.person.personList);
  const dispatch = useDispatch();

  const handleID = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();
    input.onchange = () => {
      const file = input.files[0];
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = async() => {
        const base64 = fileReader.result;
        const index = base64.indexOf(",") + 1;
        const base64Data = base64.substring(index);

      const AK='SKD0QOUFOBvlEKqTz3yhGKAP'
      const SK='sYS8DIo8BmWE5ABPcCpSlM4KXPAik6ZY'
        function getAccessToken() {
          let options = {
            method: "POST",
            url:
              "/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=" +
              AK +
              "&client_secret=" +
              SK,
          };
          return new Promise((resolve, reject) => {
            axios(options)
              .then((res) => {
                resolve(res.data.access_token);
              })
              .catch((error) => {
                reject(error);
              });
          });
        }

       async function getData(){
        var options = {
        method: 'POST',
        url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + await getAccessToken(),
        headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                Accept: 'application/json'
        },
        data: {
                id_card_side: 'front',
                image:base64Data,
                detect_ps: 'false',
                detect_risk: 'false',
                detect_quality: 'false',
                detect_photo: 'false',
                detect_card: 'false',
                detect_direction: 'false'
        }
    };

        return axios(options)
         
       }

       const res = await getData()
      console.log(res)
      
        const data={
            id:Math.random().toString(),
             name:res.data.words_result['姓名'].words,
             code:res.data.words_result['公民身份号码'].words,
             state:false
        }

        dispatch(addPerson(data))

      };
    };
  };
  return (
    <div>
      <div
        style={{
          width: "100%",
          height: "200%",
          background: "#fff",
          float: "left",
          zIndex: 99999,
          translateY: "50%",
        }}
      >
        <Button block color="primary" onClick={handleID}>
          识别身份证
        </Button>
        <Form
          layout="horizontal"
          onFinish={onFinish}
          footer={
            <Button type="submit" block color="primary">
              确定
            </Button>
          }
        >
          <Form.Item
            label="姓名"
            name="username"
            rules={[{ required: true, message: "姓名不能为空" }]}
          >
            <Input placeholder="填写姓名"></Input>
          </Form.Item>
          <Form.Item
            label="证件类型"
            name="type"
            rules={[{ required: true, message: "证件类型不能为空" }]}
          >
            <Input placeholder="二代身份证"></Input>
          </Form.Item>
          <Form.Item
            label="身份证"
            name="id"
            rules={[{ required: true, message: "身份证不能为空" }]}
          >
            <Input placeholder="填写身份证号码"></Input>
          </Form.Item>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: "手机号不能为空" },
              { pattern: /1[3-9]\d{9}/, message: "手机号必须11位" },
            ]}
          >
            <Input placeholder="填写11位手机号"></Input>
          </Form.Item>
        </Form>

        <Button block color="primary" onClick={close}>
          取消
        </Button>

        <CellGroup>
          {list.map((v) => {
            return (
              <Cell
                key={v.id}
                title={
                  <div style={{ display: "flex" }}>
                    <Checkbox
                      onClick={() => dispatch(switchPerson(v))}
                    ></Checkbox>
                    {v.name}-{v.code}
                  </div>
                }
              ></Cell>
            );
          })}
        </CellGroup>
      </div>
    </div>
  );
}

export default Index;
